﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Polaris.Common.FilterAttribute
{
    public static class HttpContextExtensions
    {
        /// <summary>
        /// 获取token中用户id
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public static string GetUserId(this HttpContext context)
        {
            return context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value
                ?? throw new InvalidOperationException("用户ID未找到");
        }

        /// <summary>
        /// 获取token中的用户角色
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetUserRole(this HttpContext context)
        {
            return context.User.FindFirst(ClaimTypes.Role)?.Value
                ?? "guest";
        }

        /// <summary>
        /// 获取token中用户身份认证信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="context"></param>
        /// <param name="claimType"></param>
        /// <returns></returns>
        public static T GetClaimValue<T>(this HttpContext context, string claimType)
        {
            var claimValue = context.User.FindFirst(claimType)?.Value;
            return (T)Convert.ChangeType(claimValue, typeof(T));
        }
    }
}
